<template>
  <el-row>
    <el-col :span="5" style="height: 100%; padding-left: 20px; padding-top: 20px; border-right: 1px solid #dfe6ec">
      <customTree :ancestralId="treeQuery.ancestralId" :btnTitle="' 添加顶级节点 '" @getId="getId" :type="true"
        @getTree="getTree" :expandType="'1'" />
    </el-col>
    <el-col :span="19">
      <div class="app-container">
        <div class="filter-container">
          <div class="filter-item">
            <span class="span">数据源名称 </span>
            <el-input v-model="listQuery.name" placeholder="请输入数据源名称" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">数据源类型 </span>
            <el-select v-model="listQuery.dbType" clearable placeholder="请选择数据源类型" style="width: 200px">
              <el-option v-for="item in dictList('datasource_type')" :key="'type' + item.label" :label="item.label"
                :value="item.value" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="span">状态 </span>
            <el-select v-model="listQuery.status" clearable placeholder="请选择开启状态" style="width: 200px">
              <el-option v-for="item in dictList('is_use')" :key="'type' + item.label" :label="item.label"
                :value="item.value" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="span">元数据同步 </span>
            <el-select v-model="listQuery.isSync" clearable placeholder="请选择同步状态" style="width: 200px">
              <el-option v-for="item in dictList('is_sync')" :key="'type' + item.label" :label="item.label"
                :value="item.value" />
            </el-select>
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>

          <el-button v-waves class="filter-item" icon="el-icon-refresh" @click="handleRest">{{ $t('table.rest')
            }}</el-button>
          <el-button v-waves v-permission="['metadata:source:add']" plain class="filter-item" style="margin-left: 10px"
            type="primary" icon="el-icon-edit" @click="handleCreate">
            {{ $t('table.add') }}
          </el-button>
          <el-button v-waves v-permission="['metadata:source:delete']" plain class="filter-item"
            style="margin-left: 10px" type="danger" icon="el-icon-delete" @click="handleBathDelete">
            {{ $t('table.delete') }}
          </el-button>
          <el-button v-waves v-permission="['metadata:source:import']" class="filter-item" type="primary"
            icon="el-icon-upload2" @click="handleImport">
            {{ $t('table.import') }}
          </el-button>
          <el-button v-waves v-permission="['metadata:source:export']" :loading="downloadLoading" class="filter-item"
            type="primary" icon="el-icon-download" @click="handleExport">
            {{ $t('table.export') }}
          </el-button>
        </div>

        <el-table ref="table" :key="tableKey" v-loading="listLoading" element-loading-text="正在加载，请稍后" :data="list"
          border fit highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" align="center" width="50" label="序号" />
          <!-- <el-table-column align="center" label="拖拽" width="80">
            <template slot-scope="{}">
              <svg-icon class="drag-handler" icon-class="drag" />
            </template>
</el-table-column> -->
          <el-table-column label="数据源名称" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据源类型" min-width="150px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.dbType | dictLabel('datasource_type') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="150px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.status | dictLabel('is_use') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="元数据同步" min-width="150px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.isSync | dictLabel('is_sync') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="数据源连接信息" min-width="150px">
                <template slot-scope="{row}">
                  <span>{{ row.dbSchema }}</span>
                </template>
              </el-table-column>
          -->
          <el-table-column label="操作" fixed="right" align="center" min-width="230"
            class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-button v-permission="['metadata:source:update']" type="text" size="small" icon="el-icon-edit"
                @click="handleUpdate(row)">
                {{ $t('table.edit') }}
              </el-button>
              <!--          <el-button v-permission="['metadata:source:update']" type="text" size="small" icon="el-icon-edit" @click="handleLook(row)">-->
              <!--            {{ $t('table.look') }}-->
              <!--          </el-button>-->
              <!-- <el-button v-permission="['metadata:source:sync']" type="text" size="small" icon="el-icon-edit" @click="handleSync(row)">
                元数据同步
              </el-button> -->
              <el-button v-permission="['metadata:source:sync']" type="text" size="small" icon="el-icon-folder-opened"
                @click="handleSync111(row)">元数据同步 </el-button>
              <el-button v-permission="['metadata:source:delete']" type="text" size="small" icon="el-icon-delete"
                class="delete-text-btn" @click="handleDelete(row, 'deleted')">
                {{ $t('table.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <import ref="import" :treeList="treeList" template-url="/system/metadata/source/template"
          import-url="/system//metadata/source/import" @refreshList="getList" />
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
          :page-sizes="pageArray" @pagination="getList" />

        <source-form ref="form" @refreshList="getList" />
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { deletesource, fetchsourceList, exportsource, syncsource, syncColumn } from '@/api/metadata/source/source'
import { deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'
import Import from '@/components/Import/import'
import waves from '@/directive/waves'
import permission from '@/directive/permission/permission'
import sourceForm from './sourceForm'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import customTree from '@/components/customTree/index.vue'
import dayjs from 'dayjs'
export default {
  name: 'sourceList',
  components: { sourceForm, Pagination, Import, customTree },
  directives: { waves, permission },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        sourceName: undefined,
        dbType: undefined,
        status: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '15',
      },
      treeList: [],
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      currentNodekey: '',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },

  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  methods: {
    getId(data) {
      this.listQuery.ancestralId = '15'
      this.listQuery.directoryId = data.id
      this.getList()
    },
    getTree(data) {
      this.treeList = data
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    getList() {
      this.listLoading = true
      fetchsourceList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.setSort()
        this.listLoading = false
      })
    },
    handleCreate() {
      if (this.listQuery.directoryId) {
        this.$refs.form.handleCreate(this.listQuery.directoryId)
      } else {
        this.$message.warning('请选择目录')
      }
    },
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row.id)
    },
    handleLook(row) {
      this.$refs.form.handleLook(row.id)
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSync(row) {
      syncsource(row.id).then((res) => {
        if (res.data.code === 0) {
          this.getList()
          this.$message.success(res.data.msg)
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    handleSync111(row) {
      syncColumn(row.id).then((res) => {
        if (res.data.code === 0) {
          this.getList()
          this.$message.success(res.data.msg)
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true

      this.download('/system/metadata/source/export', { ids: this.ids }, 'post', `目标数据库管理-${dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")}.xlsx`)
      setTimeout(() => {
        this.downloadLoading = false
      }, 6)
      // exportsource(this.ids).then((response) => {
      //   this.downloadLoading = true
      //   if (response.data.code === 0) {
      //     import('@/vendor/Export2Excel').then((excel) => {
      //       excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
      //       this.downloadLoading = false
      //     })
      //   } else {
      //     this.$message.error(response.data.msg)
      //   }
      // })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      if (this.listQuery.directoryId) {
        this.listQuery.page = 1
        this.getList()
      } else {
        this.$message.warning('请选择目录')
      }
    },
    handleRest() {
      this.listQuery = {
        sourceName: undefined,
        dbType: undefined,
        status: undefined,
        isSync: undefined,
        directoryId: this.listQuery.directoryId,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      }
      this.getList()
    },
    funindex(data) {
      var ids = []
      data.forEach((item) => {
        // 将当前对象的 id 添加到 ids 数组中
        ids.push(item.id)
        // 如果当前对象有 children 属性并且是一个数组，则递归调用 getAllIds 函数
        if (item.children && Array.isArray(item.children)) {
          // 递归调用 getAllIds 函数，将结果合并到 ids 数组中
          ids = ids.concat(this.funindex(item.children))
        }
      })
      return ids
    },
    handleNodeClick(data) {
      this.listQuery.directoryId = data.id
      console.log(this.listQuery.directoryId)
      this.getList()
    },

    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => { })
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },

  },
}
</script>
<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}

.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
